import Taro from "@tarojs/taro"

function locate(success: IFn, fail: IFn) {
  Taro.showLoading({
    title: "定位中..."
  })
  Taro.getLocation({
    type: "gcj02",
    success(result) {
      console.log("getLocation", result)
      const ret: IGetPositionRet = {
        province: result.province,
        cityName: result.city,
        lat: result.latitude,
        lng: result.longitude,
        mapType: 1
      }
      locateTip("定位成功")
      success(ret)
    },
    fail: err => {
      console.log("Taro.getLocation--error", err)
      Taro.showToast({
        title: "获取定位失败,请检查位置授权是否开启",
        icon: "none"
      })
      fail(err)
    }
  })
}
function locateTip(title: string) {
  Taro.hideLoading()
  Taro.showToast({
    title,
    icon: "none"
  })
}
export const getPosition = () => {
  return new Promise((resolve, reject) => {
    Taro.authorize({
      scope: "scope.userLocation",
      success() {
        locate(resolve, reject)
      },
      fail() {
        Taro.showModal({
          title: "提示",
          content: "拒绝授权位置可能会导致部分小程序功能受限, 打开授权？",
          success(result) {
            if (result.confirm) {
              Taro.openSetting({
                success({ authSetting }) {
                  if (authSetting["scope.userLocation"]) {
                    locate(resolve, reject)
                  } else {
                    locateTip("定位失败")
                    reject()
                  }
                },
                // Web 态暂不支持用户主动切换授权开关，接口调用会进入失败回调（fail）。
                fail(res) {
                  console.log("Taro.openSetting fail: ", res)
                  locateTip("定位失败")
                  reject()
                }
              })
            } else {
              locateTip("定位失败")
              reject()
            }
          }
        })
      }
    })
  })
}
